package com.ktjiaotu.action.action01;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: DABINGCHNEGJIAO
 * @CreateTime: 2025-06-06
 * @Description:
 * @Version: 1.0
 */
public class LoggingInvocationHandler implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method methodTarget = target.getClass().getMethod(method.getName());
        //判断方法是否有Log注解
        if (methodTarget.isAnnotationPresent(Log.class)) {
            String methodName = methodTarget.getName();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.now();
            System.out.println("[LOG] Method: " + methodName + " started at:" + startTime.format(dateTimeFormatter));
            Object result = method.invoke(target, args);
            LocalDateTime endTime = LocalDateTime.now();
            long millis = Duration.between(startTime, endTime).toMillis();
            System.out.println("[LOG] Method: " + methodName + " ended at:" + endTime.format(dateTimeFormatter));
            System.out.println("[LOG] Method: " + methodName + " executed in:" + millis + "ms");
            return result;
        } else {
            return method.invoke(target, args);
        }
    }


    private final Object target;

    public LoggingInvocationHandler(Object target) {
        this.target = target;
    }
}
